<template>
  <view class="verify-page">
    <view class="title">工作核验</view>
    <view class="hint">请在15分钟有效期内完成一次人脸核验</view>

    <!-- #ifdef H5 -->
    <div class="video" ref="videoWrap"></div>
    <!-- #endif -->

    <!-- #ifdef APP-PLUS || MP-WEIXIN -->
    <camera v-if="isCameraActive" device-position="front" flash="off" style="width: 100%; height: 300rpx;" @error="onCameraError"></camera>
    <!-- #endif -->

    <view class="btns">
      <button @click="toggleCamera">{{ isCameraActive ? '关闭摄像头' : '开启摄像头' }}</button>
      <button @click="start" :disabled="!isCameraActive || isSending">开始核验</button>
    </view>
    <view v-if="isSending" class="status">正在提交...</view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 安全获取页面参数
const getPageQuery = () => {
  try {
    if (typeof uni.getCurrentPages === 'function') {
      const pages = uni.getCurrentPages()
      if (pages && pages.length > 0) {
        const currentPage = pages[pages.length - 1]
        console.log('当前页面对象:', currentPage)
        console.log('页面 options:', currentPage?.options)
        console.log('页面 $page:', currentPage?.$page)
        return currentPage?.options || currentPage?.$page?.options || {}
      }
    }
  } catch (e) {
    console.warn('getCurrentPages 不可用:', e)
  }
  return {}
}

const query = getPageQuery()
console.log('工作核验页面获取到的参数:', query)
const workTimeId = ref(query.workTimeId || '')
console.log('workTimeId 值:', workTimeId.value)

// 如果从 getCurrentPages 获取不到，尝试从 URL 解析
if (!workTimeId.value) {
  try {
    // 尝试从当前页面 URL 解析参数
    const url = window?.location?.href || ''
    const urlParams = new URLSearchParams(url.split('?')[1] || '')
    const urlWorkTimeId = urlParams.get('workTimeId')
    if (urlWorkTimeId) {
      workTimeId.value = urlWorkTimeId
      console.log('从 URL 解析到 workTimeId:', urlWorkTimeId)
    }
  } catch (e) {
    console.warn('从 URL 解析参数失败:', e)
  }
}

const isCameraActive = ref(false)
const isSending = ref(false)

// H5
const videoWrap = ref(null)
const videoEl = ref(null)
const stream = ref(null)

const toggleCamera = async () => {
  if (isCameraActive.value) stop()
  else await startCamera()
}

const startCamera = async () => {
  try {
    // #ifdef H5
    const video = document.createElement('video')
    video.autoplay = true
    video.playsInline = true
    video.style.width = '100%'
    video.style.height = '300px'
    video.style.borderRadius = '12px'
    if (videoWrap.value) videoWrap.value.appendChild(video)
    videoEl.value = video
    const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } } })
    video.srcObject = mediaStream
    stream.value = mediaStream
    // #endif
    isCameraActive.value = true
  } catch (e) {
    uni.showToast({ title: '摄像头不可用', icon: 'none' })
    isCameraActive.value = false
  }
}

const stop = () => {
  // #ifdef H5
  if (stream.value) {
    stream.value.getTracks().forEach(t => t.stop())
    stream.value = null
  }
  if (videoEl.value) {
    videoEl.value.remove()
    videoEl.value = null
  }
  // #endif
  isCameraActive.value = false
}

const onCameraError = () => {
  uni.showToast({ title: '摄像头错误', icon: 'none' })
  isCameraActive.value = false
}

const captureBase64 = async () => {
  // #ifdef H5
  if (videoEl.value && videoEl.value.videoWidth && videoEl.value.videoHeight) {
    const canvas = document.createElement('canvas')
    canvas.width = videoEl.value.videoWidth
    canvas.height = videoEl.value.videoHeight
    const ctx = canvas.getContext('2d')
    ctx.drawImage(videoEl.value, 0, 0, canvas.width, canvas.height)
    return canvas.toDataURL('image/jpeg', 0.85)
  }
  // #endif
  // #ifdef APP-PLUS || MP-WEIXIN
  const cameraContext = uni.createCameraContext()
  const p = await new Promise((resolve, reject) => {
    cameraContext.takePhoto({
      quality: 'high',
      success: (res) => {
        uni.getFileSystemManager().readFile({
          filePath: res.tempImagePath,
          encoding: 'base64',
          success: (f) => resolve('data:image/jpeg;base64,' + f.data),
          fail: reject
        })
      },
      fail: reject
    })
  })
  return p
  // #endif
}

const start = async () => {
  if (!workTimeId.value) {
    uni.showToast({ title: '缺少workTimeId', icon: 'none' })
    return
  }
  isSending.value = true
  try {
    const frame = await captureBase64()
    if (!frame) throw new Error('无法采集图像')
    const token = uni.getStorageSync('accessToken')
    const res = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/work/verify',
      method: 'POST',
      header: { 'Access-Token': `Bearer ${token}` },
      data: { workTimeId: Number(workTimeId.value), frames: [frame], action: 'shake_head' }
    })
    if (res.statusCode === 200) {
      uni.showToast({ title: '核验完成', icon: 'success' })
      setTimeout(() => uni.navigateBack(), 800)
    } else {
      uni.showToast({ title: res.data?.message || '核验失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: e.message || '提交失败', icon: 'none' })
  } finally {
    isSending.value = false
  }
}

onMounted(() => {
  // 自动开摄像头
  startCamera()
})
onUnmounted(() => {
  stop()
})
</script>

<style scoped>
.verify-page{ padding:16px }
.title{ font-size:18px; font-weight:700; margin-bottom:6px }
.hint{ color:#666; font-size:13px; margin-bottom:10px }
.video{ width:100%; height:300px; border-radius:12px; background:#f0f0f0; overflow:hidden }
.btns{ display:flex; gap:8px; margin-top:10px }
.status{ margin-top:8px; color:#888 }
</style>



